"use strict";
if ("undefined" == typeof(TWB)){
	var TWB={
		//[START]-------Prefs-Manager-------//
		prefs : null,
		Cc : Components.classes,
		Ci : Components.interfaces,
		getPrefs : function(){
			try{
				if (!this.prefs) {
					this.prefs = this.prefManager.getBranch('extensions.twbooster.');
					this._prefs = this.prefManager.getDefaultBranch("extensions.twbooster.");
				}
				return this.prefs;
			}catch(e){ this.log(e,"getPrefs"); }
		},
		set_var : function(param,to){
			try{
				switch(typeof to){
					case "boolean":
						this.getPrefs().setBoolPref(param, to);
					break;
					
					case "number":
						this.getPrefs().setIntPref(param, to);
					break;
					
					case "object":
						this.getPrefs().setCharPref(param, this.encode(to));
					break;
					
					default:
						this.getPrefs().setCharPref(param, to);
					break;
				}
			}catch(e){ this.log(e,"set_var"); }
		},
		get_var : function(param,type){
			try{
				if(!param.match("_"+this.language+"_") && typeof type=="undefined"){
					type=this.DEFAULTS[param];
				}
				if(!this.getPrefs().prefHasUserValue(param)){
					if(typeof this.DEFAULTS[param]=="undefined" && !param.match(this.language)){
						throw {message:"EXCEPTION :: No default key for : "+param};
						return null;
					}
					this.set_var(param, type);
				}
				switch(typeof type){
					case "boolean":
						return this.decode(this.getPrefs().getBoolPref(param));
					break;
					
					case "number":
						return this.decode(this.getPrefs().getIntPref(param));
					break;
					
					case "object":
						return this.decode(this.getPrefs().getCharPref(param));
					break
					
					default:
						return this.getPrefs().getCharPref(param);
					break;
				}
			}catch(e){ this.log(e,"get_var"); }
		},
		decode : function(v){
			try{
				return this.nativeJSON.decode(v);
			}catch(e){
				return undefined;
			}
		},
		encode : function(v){
			return this.nativeJSON.encode(v);
		},
		//[END]-------Prefs-Manager-------//
		//[START]-------Default-Functions-------//
		log : function(erzx,type){
			var csClass=this.Cc['@mozilla.org/consoleservice;1'];
			var cs = csClass.getService(this.Ci.nsIConsoleService);
			cs.logStringMessage("[TWB]-{"+type+"} -> "+erzx.message);
			return true;
		},
		dce : function(kind){
			return document.createElement(kind);
		},
		gei : function(v){
			return window.document.getElementById(v);
		},
		compare : function(a,b,_S){
			if((typeof _S=="undefined" && a<b) || (typeof _S!="undefined" && a>b)){
				return a;
			}
			return b;
		},
		lang : function(v,ar){
			// ar can hold params that go inside the bundle defined with text and %S multiple times
			ar=(typeof ar!="undefined")?ar:[];
			try{
				return this.gei("TWB-Lang").getFormattedString(v, ar);
			}catch(e){
				// If it was not found
				return null;
			}
		},
		_window : function(match){
			match=(typeof match=="undefined")?null:match;
			// If we are locked on a window, just use it
			if(match==null && typeof TWB.Modules.Tools.Lock!="undefined"){
				match=TWB.Modules.Tools.Lock.contentWindow;
				if(typeof match.wrappedJSObject!="undefined"){
					match=match.wrappedJSObject;
				}
				return match;
			}
			
			var z=null, nxi;
			if(this.logged() && match==null){
					z=window._content;
			}
			else{
				for(nxi=0; nxi<this.WINX.frames.length; nxi++){
					if((match==null && this.logged(this.WINX.frames[nxi])) || (match!=null && this.WINX.frames[nxi].location.href.match(match))){
						z=this.WINX.frames[nxi];
						break; 
					}
				}
			}
			// Patch to directly scope into game.php
			if(z && z.location.href.match("staemme")){
				if(z.main && z.main.location.href.match("game")){
					z=z.main;
				}
				if(z.frames[0] && z.frames[0].location.href.match("game")){
					z=z.frames[0];
				}
			}
			return z;
		},
		URL : function(target){
			target=(typeof target=="undefined")?window._content:target;
			return target.document.location.href;
		},
		filterTN : function(_NL){
			var _NL_=[];
			var _i_;
			for(_i_=0; _i_<_NL.length; _i_++){
				if(_NL[_i_].nodeName!="#text"){
					_NL_.push(_NL[_i_]);
				}
			}
			return _NL_;
		},
		logged : function(target,_server){
			var test=true;
			target=(typeof target=="undefined")?window._content:target;
			_server=(typeof _server=="undefined")?this.language:_server;
			var urlu=target.document.location.href;
			var rexop1=new RegExp(_server+"\\w+\\."+this.Servers[_server]+"\/staemme\\.php");
			var rexop2=new RegExp(_server+"\\w+\\."+this.Servers[_server]+"\/game\\.php");
			if((rexop1 && rexop1.test(urlu)===false) && (rexop2 && rexop2.test(urlu)===false)){
				test=false;
			}
			return test;
		},
		premium : function(){
			if(this.logged()){
				if(this.Xpath("//*[@class='village_switch_link']",6).length==2){
					return true;
				}
			}
			return false;
		},
		World : function(full){
			if(this.logged(window._content)){
				var _tmp_=this.URL().split("."+this.Servers[this.language])[0].split("http://")[1];
				if(typeof full=="undefined"){
					return _tmp_.match(/\d+/)[0];
				}
				return _tmp_;
			}
			return null;
		},
		Load_Url : function(url,_win,nositting){
			_win=(typeof _win=="undefined")?content:_win;
			if(typeof nositting=="undefined" && url.match(/&t=\w+/)==null && this.URL().match(/&t=\w+/)){
				url+="&t="+this.URL().match(/&t=(\w+)/)[1];
			}
			_win.window.location.href=url;
		},
		Load_Master_Url : function(url,force){
			if(typeof force=="undefined" && window._content.document.location.href=="about:blank"){
				window._content.document.location.href=url;
			}
			else{
				this.WINX.openUILinkIn(url, 'tab');
			}
		},
		Xpath : function(xpath, n, target){
			try{
				target=(typeof target!="undefined") ? target : this._window().document;
				if(n==9){
					return target.evaluate(xpath,target,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;
				}
				if(n==6){
					var item;
					var arr = [];
					var xpr = target.evaluate(xpath, target, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
					for (var i=0; item=xpr.snapshotItem(i); i++){
						arr.push(item);
					}
					return arr;
				}
			}catch(e){ this.log(e,"Xpath"); }
		},
		WorldSet : function(sett){
			// Usage is very simple : Examples of sett
			// fake_limit
			// coord/func          Func is a member of the coord group ...
			// Lets see if the world settings are cached
			var world=this.World(true);
			if(typeof this.Servers[world.replace(/\d+/,"")]=="undefined"){
				return alert(this.lang("servernotsup"));
			}
			if(typeof this.WORLD_SET[world]=="undefined"){
				// Lets cache them 
				var link="http://"+world+"."+this.Servers[world.replace(/\d+/,"")]+"/interface.php?func=get_config";
				var req = new XMLHttpRequest();
				req.open("GET", link, false);
				req.send(null);
				this.WORLD_SET[world]=req.responseXML;
			}
			// Make sure all arguments are there so that XPF won't bark
			if(typeof sett!="undefined"){
				// Load a particular setting
				var nsResolver = this.WORLD_SET[world].createNSResolver(this.WORLD_SET[world].ownerDocument==null?this.WORLD_SET[world].documentElement:this.WORLD_SET[world].ownerDocument.documentElement);
				var element = this.WORLD_SET[world].evaluate('//'+sett,this.WORLD_SET[world],nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;
				if(element!==null){
					return element.textContent;
				}
				else{
					return null;
				}
			}
		},
		Notify : function(msg,anchor){
			if(msg==false){
				this.Notify_.remove();
			}
			else{
				this.Notify_=PopupNotifications.show(gBrowser.selectedBrowser, "TWB-Notify",
					msg, anchor, {
						label: this.lang("hide_msg"),
						accessKey: this.lang("hide_msg_access"),
						callback: function() {
							this.Notify(false);
						}
					}, null);
			}
		},
		//[END]-------Default-Functions-------//
		//[START]-------Time-Functions--------//
		Time : function(){
			return Math.round((new Date()).getTime()/1000);
		},
		CheckTime : function(time,span){
			if(typeof time=="undefined") return true;
			return time>(this.Time()-span);
		},
		//[END]------=-Time-Functions--------//
		//[START]-------Core-Functions-------//
		WORLD_SET : {},
		Init : function(){
			try{
				// Initialize objects
				this.SL=(navigator.platform.indexOf("Linux")==-1 && navigator.platform.indexOf("Mac")==-1)?"\\":"/";
				this.nativeJSON=this.Cc["@mozilla.org/dom/json;1"].createInstance(this.Ci.nsIJSON);
				this.prefManager=this.Cc['@mozilla.org/preferences-service;1'].getService(this.Ci.nsIPrefService);
				this.WINX=this.Cc['@mozilla.org/appshell/window-mediator;1'].getService(this.Ci.nsIWindowMediator).getMostRecentWindow("navigator:browser");
				this.nsIFilePicker=this.Ci.nsIFilePicker;
				this.dfile=this.Cc["@mozilla.org/file/local;1"].createInstance(this.Ci.nsILocalFile);
				// Start the processor
				// gBrowser.addProgressListener(this.Processor.Listener,this.Ci.nsIWebProgress.NOTIFY_STATE_DOCUMENT);
				gBrowser.addProgressListener(this.Processor.Listener); // Update to 5.0
				this.jsLoader=this.Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(this.Ci.mozIJSSubScriptLoader);
				this.jsLoader.loadSubScript("chrome://twbooster/content/jquery.js", TWB);
				this.$=$;
				this.jQuery=jQuery;
				jQuery.noConflict();
				// Init toolbar on first run
				try {
					if(this.get_var("firstrun",true)==true){
						var Bar=document.getElementById("TWB-Toolbar");
						var toolbox=document.getElementById("navigator-toolbox");
						var buttons=Array.prototype.slice.call(toolbox.palette.getElementsByClassName("twb-button"));
						for(var i=0; i<buttons.length; i++){
							var myId=buttons[i].id;
							var curSet=Bar.currentSet.split(",");
							if(curSet.indexOf(myId)==-1){
								Bar.insertItem(myId, null, null, false);
								curSet.push(myId);
							}
						}
						Bar.setAttribute("currentSet",Bar.currentSet);
						document.persist(Bar.id, "currentSet");
						try{
							window.setTimeout(function(){
								BrowserToolboxCustomizeDone(true);
							},0);
						}catch(e){}
						this.set_var("firstrun",false);
					}
				}
				catch(e) {}
			}catch(e){ this.log(e,"Init"); }
		},
		Processor : {
			STATE_START : this.Ci.nsIWebProgressListener.STATE_START,
			STATE_STOP : this.Ci.nsIWebProgressListener.STATE_STOP,
			processes : {},
			Listener : {
				QueryInterface : function(aIID) {
					if(aIID.equals(this.Ci.nsIWebProgressListener) ||
					   aIID.equals(this.Ci.nsISupportsWeakReference) ||
					   aIID.equals(this.Ci.nsISupports)){
						return this;
					}
					throw Components.results.NS_NOINTERFACE;  
				},
				onStateChange : function(aWebProgress,aRequest,aFlag,aStatus){
					if(aFlag & TWB.Processor.STATE_STOP && aRequest!==null && aRequest.URI){
						TWB.Processor.exec(aWebProgress.DOMWindow,aRequest.URI.spec);
						return 0;
					}
					if(aFlag & TWB.Processor.STATE_START){
						return 0;
					}
				},
				onLocationChange : function(aWebProgress,aRequest,aURI){return 0;},
				onProgressChange : function(aWebProgress,aRequest,curSelf,maxSelf,curTot,maxTot){return 0;},
				onStatusChange : function(aWebProgress,aRequest,aStatus,aMessage){return 0;},
				onSecurityChange : function(aWebProgress,aRequest,aState){return 0;}
			},
			start : function(nemo,funct,targetURL,KILL){
				if(typeof TWB.Processor.processes[nemo]!="object"){
					TWB.Processor.processes[nemo]={"name":nemo,"function":funct,"target":targetURL,"kill":KILL};
				}
			},
			stop : function(nemo){
				if(typeof TWB.Processor.processes[nemo]=="object"){
					delete TWB.Processor.processes[nemo];
				}
			},
			exec : function(pWIN,pURL){
				TWB._PRO=TWB.Processor.processes;
				for(TWB._PXID in TWB._PRO){
					try{
						if(TWB._PRO[TWB._PXID]["target"]=="*" || (typeof TWB._PRO[TWB._PXID]["target"]=="string" && pURL.indexOf(TWB._PRO[TWB._PXID]["target"])>-1)){
							var func=TWB._PRO[TWB._PXID].function.split(".");
							var tmp=TWB;
							var iter;
							for(iter=0; iter<func.length; iter++){
								tmp=tmp[func[iter]];
							}
							if(TWB._PRO[TWB._PXID]["kill"]==true){
								window.setTimeout("TWB.Processor.stop('"+TWB._PRO[TWB._PXID]["name"]+"');",300);
							}
							tmp.apply(TWB);
						}
					}catch(e){
						TWB.log(e,"Processor::"+TWB._PXID);
					}
				}
			}
		}
		//[END]-------Core-Functions-------//
	};
}

window.addEventListener("load",function(){ TWB.Init(); },false);